package com.wmlive.hhvideo.heihei.mainhome.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.base.BaseCompatActivity;
import com.wmlive.hhvideo.common.network.HttpConstant;
import com.wmlive.hhvideo.heihei.beans.main.RefreshCommentBean;
import com.wmlive.hhvideo.heihei.beans.main.VideoCommentResponse;
import com.wmlive.hhvideo.heihei.mainhome.presenter.CommentPresenter;
import com.wmlive.hhvideo.utils.DeviceUtils;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;
import cn.wmlive.hhvideo.rxbuslib.RxBus2;

/**
 * Created by lsq on 6/15/2017.
 * 评论页面
 */
public class CommentActivity extends BaseCompatActivity<CommentPresenter> implements
        CommentPresenter.ICommentView, View.OnLayoutChangeListener {

    @BindView(R.id.llRootView)
    LinearLayout llRootView;
    @BindView(R.id.viewBlankHolder)
    View viewBlankHolder;
    @BindView(R.id.etComment)
    EditText etComment;
    @BindView(R.id.tvSend)
    TextView tvSend;

    public static final int COMMENT_REQUEST_CODE = 100;
    private boolean isNeedResult = true;
    private int currentPosition;

    private String userName;
    private long userId;
    private long videoId;
    private int keyboardHeight;

    public static void startCommentActivity(Activity ctx, boolean isNeedResult, int position, long videoId, String userName, long userId) {
        Intent intent = new Intent(ctx, CommentActivity.class);
        intent.putExtra("isNeedResult", isNeedResult);
        intent.putExtra("position", position);
        intent.putExtra("videoId", videoId);
        intent.putExtra("userName", userName);
        intent.putExtra("userId", userId);
        ctx.startActivityForResult(intent, CommentActivity.COMMENT_REQUEST_CODE);
    }

    @Override
    protected CommentPresenter getPresenter() {
        return new CommentPresenter(this);
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_comment;
    }

    @Override
    protected void initData() {
        super.initData();
        videoId = getIntent().getLongExtra("videoId", 0);
        if (videoId > 0) {
            keyboardHeight = DeviceUtils.getScreenWH(this)[1] / 3;
            llRootView.addOnLayoutChangeListener(this);
            currentPosition = getIntent().getIntExtra("position", 0);
            userName = getIntent().getStringExtra("userName");
            isNeedResult = getIntent().getBooleanExtra("isNeedResult", true);
            userId = getIntent().getLongExtra("userId", 0);
            viewBlankHolder.setOnClickListener(this);
            tvSend.setOnClickListener(this);
            if (userId > 0) {
                etComment.setHint("回复：" + userName);
            }
            etComment.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    String text = etComment.getText().toString().trim();
                    if (text.length() > 100) {
                        text = text.substring(0, 100);
                        etComment.setText(text);
                        etComment.setSelection(text.length());
                        showToast("评论最多100个字");
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                    String text = s.toString().trim();
                    KLog.i("=======text:" + text + "\nlength:" + text.length());
                    tvSend.setEnabled(!TextUtils.isEmpty(text));
                }
            });
        } else {
            toastFinish();
        }
    }


    @Override
    protected void onSingleClick(View v) {
        switch (v.getId()) {
            case R.id.tvSend:
                String comment = etComment.getText().toString().trim();
                if (!TextUtils.isEmpty(comment)) {
                    loading();
                    StringBuilder stringBuilder = new StringBuilder();
                    if (!TextUtils.isEmpty(userName)) {
                        stringBuilder.append("回复").append(userName).append("：");
                    }
                    stringBuilder.append(comment);
                    presenter.comment(videoId, stringBuilder.toString(), null, userId);
                } else {
                    showToast("评论不能为空");
                }
                break;
            case R.id.viewBlankHolder:
                finish();
                break;
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //设置adjustSize才生效
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyboardHeight)) {
            KLog.i("键盘弹起");
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyboardHeight)) {
            KLog.i("键盘关闭");
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        RxBus2.get().send(GlobalParams.EventType.TYPE_RESET_NEED_PAUSE);
    }

    @Override
    public void onCommentOk(VideoCommentResponse bean) {
        dismissLoad();
        if (isNeedResult) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("result", bean);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
        } else {
            RxBus2.get().send(GlobalParams.EventType.TYPE_REFRESH_RECOMMEND_COMMENT_COUNT,
                    new RefreshCommentBean(currentPosition, videoId, bean.getData_count() != null ? bean.getData_count().getComment_count() : 0));
        }
        finish();
    }

    @Override
    public void onCommentFailed(String msg) {
        RxBus2.get().send(GlobalParams.EventType.TYPE_WORK_DELETED, videoId);
        ToastUtil.showToast(msg);
        finish();
    }

    @Override
    public void onRequestDataError(int requestCode, String message) {
        dismissLoad();
        if (requestCode == HttpConstant.TYPE_FETCH_COMMENT) {
            showToast("发表评论失败，请稍后再试");
        } else {
            super.onRequestDataError(requestCode, message);
        }
    }
}
